package com.hskn.hss.module.tlequipmonitor.controller;


import com.alibaba.fastjson.JSONObject;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.module.tlequipmonitor.service.TlEquipMonitorService;
import com.hskn.hss.utils.redis.RedisUtil;
import com.hskn.hss.utils.redis.key.EquipMonitorKey;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lny
 * @since 2021-11-17
 */
@Api(tags = {"-tl_equipmonitor"}, description = "设备监控")
@Slf4j
@RestController
@RequestMapping("/hss/tlequipmonitor")
public class TlEquipMonitorController {

    @Autowired
    private TlEquipMonitorService tlEquipMonitorService;

    @ApiOperation(value = "设备监控", notes = "设备监控")
    @RequestMapping(value = "monitor", method = RequestMethod.POST)
    public AjaxResult<Object> monitor(@RequestBody JSONObject json) {
        Integer page = json.getInteger("page");
        Integer size = json.getInteger("size");
        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }
        List list = RedisUtil.get(EquipMonitorKey.token, "", List.class);
        Integer pages = 0;
        Integer total = 0;
        if (!CollectionUtils.isEmpty(list)) {
            total = list.size();
            pages = total % size != 0 ? total / size + 1 : total / size;
        }
        int fromIndex = (page - 1) * size;
        int toIndex = 0;
        if (pages.equals(page)) {
            toIndex = total;
        } else {
            toIndex = fromIndex + size;
        }
        List listResult = new ArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            listResult = list.subList(fromIndex, toIndex);
        }
        JSONObject result = new JSONObject();
        result.put("total", total);
        result.put("size", size);
        result.put("pages", pages);
        result.put("current", page);
        result.put("list", listResult);
        return AjaxResult.success(result);
    }

    @ApiOperation(value = "刷新", notes = "刷新")
    @RequestMapping(value = "refresh", method = RequestMethod.GET)
    public AjaxResult<Object> refresh() {
        tlEquipMonitorService.refresh();
        return AjaxResult.success();
    }

}

